package com.piece.core.oauth.social;

import com.piece.core.framework.util.net.URLUtil;
import com.piece.core.framework.util.string.JsonUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.oauth.enums.AuthExtendSource;
import me.zhyd.oauth.enums.AuthUserGender;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Service
@ConditionalOnProperty(prefix = "justauth", value = "enabled", havingValue = "true", matchIfMissing = true)
public class AuthSocialService {

    @Autowired
    protected AuthRequestFactory authRequestFactory;

    /**
     * 获得社交平台的授权 URL
     *
     * @param source 社交平台的类型 {@link AuthExtendSource}
     * @param redirect 重定向 URL
     */
    public String getAuthorizeUrl(String source, String redirect, String state) {
        AuthRequest authRequest = authRequestFactory.get(source);
        String authorizeUri = authRequest.authorize(state);
        if (StringUtil.isNotEmpty(redirect)) {
            authorizeUri = URLUtil.buildQuery(authorizeUri, "redirect_uri", redirect);
        }

        return authorizeUri;
    }

    /**
     * 授权获得对应的社交用户
     *
     * @param source 社交平台的类型 {@link AuthExtendSource}
     * @param code   授权码
     * @param state  state
     */
    public AuthSocialUserDTO getSocialUserInfo(String source, String code, String state) {
        AuthUser authUser = getAuthUser(source, code, state);
        Assert.notNull(authUser, "三方用户不能为空");

        AuthSocialUserDTO user = AuthSocialUserDTO.builder()
                .type(source)
                .code(code)
                .state(state)
                .openid(authUser.getUuid())
                .accessToken(authUser.getToken().getAccessToken())
                .loginName(authUser.getUsername())
                .nickname(authUser.getNickname())
                .avatar(authUser.getAvatar())
                .email(authUser.getEmail())
                .rawTokenInfo(JsonUtil.toJson(authUser.getToken()))
                .rawUserInfo(JsonUtil.toJson(authUser.getRawUserInfo()))
                .build();

        AuthUserGender gender = authUser.getGender();
        if (null != gender) {
            switch (gender) {
                case MALE:
                    user.setGender("0");
                    break;
                case FEMALE:
                    user.setGender("1");
                    break;
                default:
                    user.setGender("2");
            }
        } else {
            user.setGender("2");
        }

        return user;
    }

    /**
     * 请求社交平台，获得授权的用户
     */
    private AuthUser getAuthUser(String source, String code, String state) {
        AuthRequest authRequest = authRequestFactory.get(source);
        AuthCallback authCallback = AuthCallback.builder().code(code).state(state).build();
        AuthResponse<?> authResponse = authRequest.login(authCallback);
        if (!authResponse.ok()) {
            throw new RuntimeException(authResponse.getMsg());
        }
        return (AuthUser) authResponse.getData();
    }
}
